from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model

User = get_user_model()

class ReciteSession(models.Model):
    """
    记录用户一次背诵批次的信息
    """

    class SessionType(models.TextChoices):
        RECITATION = 'recitation', 'Recitation'
        SCHEDULED_REVIEW = 'scheduled_review', 'Scheduled Review'
        WORD_CHALLENGE = 'word_challenge', 'Word Challenge'

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recite_sessions')
    start_time = models.DateTimeField(auto_now_add=True)
    end_time = models.DateTimeField(null=True, blank=True)
    total_words = models.PositiveIntegerField(default=0)       # 本次背诵的单词总数
    completed_words = models.PositiveIntegerField(default=0)   # 本次实际完成背诵的单词数
    session_type = models.CharField(max_length=20, choices=SessionType.choices, default=SessionType.RECITATION)

    def __str__(self):
        return f"ReciteSession #{self.id} - user: {self.user.email} - type: {self.session_type}"

    def check_completion(self):
        """
        检查会话是否已完成，如果完成则设置 end_time
        """
        if self.completed_words >= self.total_words and self.end_time is None:
            self.end_time = timezone.now()
            self.save()


class ReciteRecord(models.Model):
    """
    记录用户背诵的具体单词情况
    """

    class WordType(models.TextChoices):
        NOUN = 'N', 'Noun'
        VERB = 'V', 'Verb'
        ADJ = 'A', 'Adjective'
        OTH = 'O', 'Other'

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recite_records')
    session = models.ForeignKey('ReciteSession', on_delete=models.SET_NULL,
                                related_name='records', null=True, blank=True)
    word_type = models.CharField(max_length=1, choices=WordType.choices)
    word_id = models.PositiveIntegerField()  # 对应 Noun/Verb/Adjective/Other 表中的 PK

    is_known = models.BooleanField(default=False)  # 本次背诵时，用户是否认识
    last_study_time = models.DateTimeField(auto_now=True)      # 最近一次学习/复习时间
    study_count = models.PositiveIntegerField(default=0)       # 用户已学习/复习次数
    next_review_date = models.DateField(null=True, blank=True)  # 下次复习日期
    stage = models.IntegerField(default=1)  # 新增 stage 字段，用于存储阶段信息

    def __str__(self):
        return f"ReciteRecord (user={self.user.email}, word_type={self.word_type}, word_id={self.word_id})"

    def schedule_next_review(self):
        """
        根据复习次数安排下一次复习日期（1天、3天、7天、10天、15天）
        """
        intervals = [1, 2, 5, 7, 10, 15, 30]  # 可根据需求扩展
        # 如果 study_count 超过 intervals 列表长度，就取最后一个间隔
        idx = min(self.study_count, len(intervals)) - 1
        if idx < 0:
            idx = 0
        days_to_add = intervals[idx]
        self.next_review_date = (timezone.now() + timezone.timedelta(days=days_to_add)).date()
        self.save()
